import { defineStore } from 'pinia'
import { setItem, getItem } from "@/general/storage";

export const useAuthStore = defineStore('auth', {
    state: () => { 
        return {
            isAuthenticated: getItem("isAuthenticated") || false,
            user: getItem("user") || {},
            token: getItem("token") || {},
        }
    },
    getters: {
        getAuthenticated: (state) => state.isAuthenticated,
        getUser: (state) => state.user.nick
    },
    actions: {
        setAuth(isAuth: boolean) {
            if (isAuth) {
                this.isAuthenticated = isAuth; 
                setItem("isAuthenticated", true)
            } else {
                this.isAuthenticated = false;
                setItem("isAuthenticated", false)
            }
        },
        setToken(token: String) {
            if (token) {
                setItem("token", token)
                this.token = token;
            } else {
                this.token = "";
            }
        },
        setUser(user: any) { 
            if (user) {
                this.user = user;
                setItem("user", user)
            } else {
                this.user = {};
            }
        }
    },
})
